package com.myself.common.config;

import org.ktorm.database.Database
import org.ktorm.database.Transaction
import org.ktorm.database.TransactionIsolation
import org.ktorm.database.TransactionManager
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
import java.sql.Connection
import javax.sql.DataSource

@Configuration
open class KtormConfiguration {
    @Autowired
    lateinit var dataSource: DataSource

    @Bean
    open fun database(): Database {
        return Database.connectWithSpringSupport(dataSource)
    }


}
@Configuration
open class SpringManagedTransactionManager(val dataSource: DataSource) : TransactionManager {

    val dataSourceProxy = dataSource as? TransactionAwareDataSourceProxy ?: TransactionAwareDataSourceProxy(dataSource)

    override val defaultIsolation get() = TransactionIsolation.REPEATABLE_READ

    override val currentTransaction: Transaction? = null

    override fun newTransaction(isolation: TransactionIsolation?): Nothing {
        val msg = "Transaction is managed by Spring, please use Spring's @Transactional annotation instead."
        throw UnsupportedOperationException(msg)
    }

    override fun newConnection(): Connection {
        return dataSourceProxy.connection
    }
}